package com.zk.atm.service.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

import com.bpms.common.CommonUtil;
import com.bpms.common.Constants;
import com.bpms.common.JdbcWorker;
import com.bpms.common.VO;
import com.bpms.eai.PackTool;
import com.bpms.esb.IService;
import com.zk.atm.forms.AtmpDeviceStatusForm;
import com.zk.atm.service.IAtmpDeviceStatusService;
import com.zk.atm.utils.AccessDBConnection;
import com.zk.atm.utils.ConstantsAtmp;
import com.zk.atm.utils.PrimaryKeyUtil;
import com.zk.atm.utils.StringUtil;

public class AtmpDeviceStatusServiceImpl extends PackTool
         implements IService,IAtmpDeviceStatusService {
	public static final Logger logger=Logger.getLogger(AtmpDeviceStatusServiceImpl.class);
	@Override
	public VO exec(VO args) {
		byte[] body=(byte[])args.getObj("body");
		VO r=new VO();
		try{
			r.voType="ATM.SaveAtmpDeviceStatus";
			String devstatus=this.getField(body, body.length, "devstatus");
			String DEVICENO=this.getField(body, body.length, "1001");  //设备号                     
			String NETNUM=this.getField(body, body.length, "1002");   //网点号               
			String BillDateTime=this.getField(body, body.length, "1003");    //日期时间                                                
			
			//r.setAttr("BILLNO",BILLNO);
			CommonUtil.debug("ATM.SaveAtmpDeviceStatus parseBuffer");
			return r;
		}catch(Exception e){
			CommonUtil.debug("SaveAtmpDeviceStatus exception",e);
			return null;
		}
	}
    /**
     * @author zengqun
     * @remark 解析客户端http发送上来的状态，写入数据库源状态表、历史表、当前状态表中
     * 源状态表是持续插入；历史表是从源数据表中行列倒置，每上来一次状态，则插入1条；当前状态表，始终更新。
     * @date 2012-9-26
     * @version 1.0
     */
	public boolean saveDevcieStatus(AtmpDeviceStatusForm statusForm)
			throws Exception {
		boolean isSuccess=false;
		try {
			//解析http发送上来的所有状态值
			Map status_map=this.getStatusListByStatusForm(statusForm);
			//打印拆分后的map:状态值
			StringUtil.printMap(status_map);
			//生成父记录的主键
			String device_ip=StringUtil.getPropertyValue(status_map.get(ConstantsAtmp.ATMP_DEVICE_STATUS_DEVICE_IP_NAME));
			String parent_device_status_id=this.getParentStatusId(device_ip);
			//把其它状态，与此主主键关联上。
			isSuccess=this.saveDeviceStatusByParentKeyAndMap(parent_device_status_id,status_map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return isSuccess;
	}
	
	public boolean saveDeviceStatusByParentKeyAndMap(String parent_key,Map statusMap) throws Exception {
		boolean is_success = false;
		parent_key=StringUtil.getPropertyValue(parent_key);
		if (parent_key.equals("")||statusMap == null || statusMap.size() == 0) {
			return false;
		}
		Connection conn = AccessDBConnection.getConnection();
		Map<String,Connection> connectionMap=new HashMap<String,Connection>();
		//存放conn,由主方法来获取，释放conn
		connectionMap.put(ConstantsAtmp.ATMP_CONNECTION_NAME, conn);
		String table_name = "atmp_device_status_original";
		try {
			String sql = "insert into " + table_name + "  "
					+ "(device_status_original_id,p_device_status_original_id, "
					+ "device_column_key,device_column_value,time_mark ) "
					+ "values(?,?,?,?," + getDateValue() + ")";
			PreparedStatement pst = conn.prepareStatement(sql);
			conn.setAutoCommit(false);
			Iterator it = statusMap.entrySet().iterator();
			while (it.hasNext()) {
				Entry<String,String> e = (Entry<String,String>) it.next();
				String key = (String) e.getKey();
				String value = (String) e.getValue().toString();
				//获取主键，根据表名，找到对应的序列配置，生成处境的主键。
				pst.setString(1, PrimaryKeyUtil.getPrimaryKey(table_name, connectionMap));
				pst.setString(2, parent_key);
				pst.setString(3, key);
				pst.setString(4, value);
				pst.addBatch();
			}
			pst.executeBatch();
			conn.commit();
			pst.clearBatch();
			is_success=true;
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			AccessDBConnection.closeConnection(conn);
		}
		return is_success;
	}

	/**
	 * @remark 根據device_ip生成主鍵id值，把其它子狀態與此主id值相互关联；形成父子结构，便于状态行列倒置。
	 * @param deviceIp
	 * @return
	 * @throws Exception
	 */
	public String getParentStatusId(String deviceIp) throws Exception {
		Connection conn = AccessDBConnection.getConnection();
		Map map=new HashMap();
		//把connection放在主方法里面，获取，释放。
		map.put(ConstantsAtmp.ATMP_CONNECTION_NAME, conn);
		String device_status_original_id="";
		try {
			Date d = new Date();
			String table_name = "atmp_device_status_original";
			String sql = "insert into " + table_name + "  "
					+ "(device_status_original_id,p_device_status_original_id, "
					+ "device_column_key,device_column_value,time_mark ) "
					+ "values(?,?,?,?," + getDateValue() + ")";
			PreparedStatement pst = conn.prepareStatement(sql);
			String primary_key = PrimaryKeyUtil.getPrimaryKey(table_name, map);
			if (primary_key.equals("")) {
				logger.error(table_name + "：getParentStatusId:获取主键异常！");
				return "";
			}
			pst.setString(1, primary_key);
			pst.setString(2, null);
			pst.setString(3, ConstantsAtmp.ATMP_DEVICE_STATUS_DEVICE_IP_NAME);
			pst.setString(4, deviceIp);
			pst.execute();
//			sql = "select *from "+table_name+" adso where adso.device_column_key='"+ConstantsAtmp.ATMP_DEVICE_STATUS_DEVICE_IP_NAME+"'"
//					+ " and adso.device_column_value='"+ deviceIp+ "'"+ " and adso.p_device_status_original_id is null";
//			PreparedStatement pst2 = conn.prepareStatement(sql);
//			ResultSet rs = pst2.executeQuery();
//			device_status_original_id = "";
//			while (rs.next()) {
//				device_status_original_id = rs.getString("device_status_original_id");
//			}
			device_status_original_id=primary_key;
			if(logger.isDebugEnabled()){
			  System.out.println("getParentStatusId:device_status_original_id="+ device_status_original_id);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			AccessDBConnection.closeConnection(conn);
		}
		return device_status_original_id;
	}
	
//	protected boolean saveDeviceStatusByMap(Map statusMap) throws Exception{
//		boolean isSuccess=false;
//		try {
//			String device_ip=StringUtil.getPropertyValue(statusMap.get(ConstantsAtmp.ATMP_DEVICE_STATUS_DEVICE_IP_NAME));
//			if(!device_ip.equals("")){
//				JdbcWorker jdbcWorker=new JdbcWorker();
//				VO status_ori_vo=new VO();
//				//" (device_status_original_id,p_device_status_original_id,device_column_key,device_column_value,time_mark )" +
//				//"  values(?,?,?,?,?);";
//			    //"  values(2,'','DeviceIp','192.168.0.188',to_date('2012-9-24','yyyy-MM-dd'));";
//				long key_id=jdbcWorker.getSeqValue("atmp_org");
//				status_ori_vo.setAttr("device_status_original_id", key_id+"");
//				status_ori_vo.setAttr("device_column_key", ConstantsAtmp.ATMP_DEVICE_STATUS_DEVICE_IP_NAME);
//				status_ori_vo.setAttr("device_column_value", device_ip);
//				status_ori_vo.setAttr("time_mark", "to_date('"+new Date().toLocaleString()+"','yyyy-MM-dd')");
//				jdbcWorker.insert(status_ori_vo);
//				isSuccess=true;
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return isSuccess;
//	}

	//解析http发送上来的状态字符串，存放到map中
	private Map<String,String> getStatusListByStatusForm(AtmpDeviceStatusForm statusForm) 
	                                            throws Exception{
		Map<String,String> status_map=new HashMap<String,String>();
		String devstatus=statusForm.getDevstatus();
		//先以|拆分
		String[] strs=devstatus.split(ConstantsAtmp.ATMP_DEVICE_STATUS_SPLIT_SIGN);
		if(!StringUtil.isEmptyStringArray(strs)){
			//取|竖线后面的字符串； 以;分号拆分
			String[] status_strs=strs[1].split(ConstantsAtmp.ATMP_DEVICE_STATUS_SPLIT_SIGN_VALUE);
			if(!StringUtil.isEmptyStringArray(status_strs)){
				for (int i = 0; i < status_strs.length; i++) {
					//对每个状态值，以:冒号拆分
					String[] each_key_value=status_strs[i].split(ConstantsAtmp.ATMP_DEVICE_STATUS_SPLIT_SIGN_KEY);
				    if(!StringUtil.isEmptyStringArray(each_key_value)){
				    	String key=each_key_value[0];
				    	String value=each_key_value[1];
				    	if(logger.isDebugEnabled()){
				    	 System.out.println("*********************getStatusListByStatusForm:key="+key+",value="+value);
				    	}
				    	status_map.put(key, value);
				    }
				}
			}
		}
		return status_map;
	}
	
	public static void main(String[] args) {
		//System.out.println(new Date().toLocaleString());
		try {
//			JdbcWorker jdbcWorker=new JdbcWorker();
//			jdbcWorker.execute("insert into atmp_device_status_original (device_status_original_id,p_device_status_original_id,device_column_key,device_column_value,time_mark )values(4,'','DeviceIp','192.168.0.188',to_date('2012-9-24','yyyy-MM-dd'))" +
//					           "insert into atmp_device_status_original (device_status_original_id,p_device_status_original_id,device_column_key,device_column_value,time_mark )values(5,'','DeviceIp','192.168.0.188',to_date('2012-9-24','yyyy-MM-dd'));" +
//					"");
//			System.out.println("patch success!");
			AtmpDeviceStatusForm form=new AtmpDeviceStatusForm();
			String devstatus="001234|DeviceIP:192.168.1.135;stamper:Nomarl;GeneralPrinter:NoSupport;IDCardReader:Fault";
			form.setDevstatus(devstatus);
//			String[] dev1=devstatus.split("\\|");
//			for (String string : dev1) {
//				System.out.println(string);
//			}
			new AtmpDeviceStatusServiceImpl().saveDevcieStatus(form);
		} catch (Exception e) {
			System.out.println("patch fault!");
			e.printStackTrace();
		}
	}  
	
	public static String getDateValue() throws Exception {
		Date d = new Date();
		return "to_date('" + d.toLocaleString() + "','yyyy-MM-dd hh24:mi:ss')";
	}
}
